package com.cinema.servlet.api;

import com.cinema.entity.User;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 检查登录状态API
 */
public class CheckLoginServlet extends HttpServlet {
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        
        PrintWriter out = response.getWriter();
        
        try {
            // 检查用户登录状态
            HttpSession session = request.getSession(false);
            User user = null;
            
            if (session != null) {
                user = (User) session.getAttribute("user");
            }
            
            if (user != null) {
                // 用户已登录
                out.print("{\"success\": true, \"message\": \"用户已登录\", \"username\": \"" + user.getUsername() + "\"}");
            } else {
                // 用户未登录
                out.print("{\"success\": false, \"message\": \"用户未登录\", \"redirect\": \"" + request.getContextPath() + "/login\"}");
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            out.print("{\"success\": false, \"message\": \"检查登录状态失败\"}");
        } finally {
            out.close();
        }
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        doGet(request, response);
    }
}
